package com.wptk.filemanager.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.wptk.filemanager.App;
import com.wptk.filemanager.BuildConfig;
import com.wptk.filemanager.R;
import com.wptk.filemanager.ad.AdLoadManager;
import com.wptk.filemanager.ad.utils.AnalyticsUtils;
import com.wptk.filemanager.model.Constant;
import com.wptk.filemanager.model.FileDataManager;
import com.wptk.filemanager.ui.base.BaseActivity;
import com.wptk.filemanager.utils.LogUtils;
import com.wptk.filemanager.utils.ThreadManager;
import com.hz.sdka.ada.AdListenera;
import com.hz.sdka.ada.Interstitiala;
import com.hz.sdka.ada.Splasha;
import com.hz.sdka.commona.bean.HZAdError;

@SuppressLint("CustomSplashScreen")
public class SplashActivity extends BaseActivity  {

    private ImageView logo;
    private TextView appName;
    private ProgressBar pb;
    private LinearLayout protocolContainerLl;
    private Button agreeBt;
    private TextView protocolTv;
    private int progress = 0;
    private ImageView cancleIv;
    private boolean showSplashAD = false;
    private boolean showIntersAD = false;
    private FrameLayout adLayout;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AnalyticsUtils.INSTANCE.logEvent("appqd");
        startLoadAd();
    }

    private void startLoadAd() {

        AdLoadManager.INSTANCE.loadSplash();
        AdLoadManager.INSTANCE.loadInterstitial();
        //AdLoadManager.INSTANCE.loadRewardedVideo();
        AdLoadManager.INSTANCE.loadNative();

        AnalyticsUtils.INSTANCE.logEvent("qd_ad");//触发启动页广告场景
        if (FileDataManager.appConfig.getFile_Config().getQdcy_ad() == 0)
            loadSplashAD();
        else
            loadSplashAndIntersAD();
    }

    private void loadSplashAndIntersAD() {
        ThreadManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                int loopNum = FileDataManager.appConfig.getFile_Config().getQdlc() > 0
                        ? FileDataManager.appConfig.getFile_Config().getQdlc()
                        : 2;
                for (int i = 0; i < loopNum; i++) {
                    SystemClock.sleep(3000);
                    if (Splasha.getInstance().isReady() && Interstitiala.getInstance().isReady()) {

                        if (Splasha.getInstance().getEcpm() > Interstitiala.getInstance().getEcpm()) {
                            showSplashAD = true;
                        } else {
                            showIntersAD = true;
                        }
                        whenLoadAD(i);
                        break;
                    } else if (Splasha.getInstance().isReady()) {
                        showSplashAD = true;
                        whenLoadAD(i);
                        break;
                    } else if (Interstitiala.getInstance().isReady()) {
                        showIntersAD = true;
                        whenLoadAD(i);
                        break;
                    }
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadAdEnd();
                    }
                });
            }
        });
    }

    private void loadSplashAD() {
        ThreadManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                int loopNum = FileDataManager.appConfig.getFile_Config().getQdlc() > 0
                        ? FileDataManager.appConfig.getFile_Config().getQdlc()
                        : 2;
                for (int i = 0; i < loopNum; i++) {
                    SystemClock.sleep(3000);

                    if (Splasha.getInstance().isReady()) {

                        whenLoadAD(i);
                        showSplashAD = true;
                        break;
                    }
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadAdEnd();
                    }
                });
            }
        });
    }

    private void loadAdEnd() {
        FileDataManager.getInstance().updateRemoteConfig();

        if (App.spUtils.getBoolean(Constant.IS_AGREE_PRIVACE, false)) {

            showAD();
        } else {
            //进入协议页面埋点
            showAgreeProtocolLayout();
        }

    }

    private void showAD() {
        LogUtils.e(TAG, "showAD   showSplashAD = " + showSplashAD + "  showIntersAD = " + showIntersAD);
        if (!showSplashAD && !showIntersAD) {
            goToHome();
            return;
        }

        if (showSplashAD) {

            AdLoadManager.INSTANCE.showSplashAd(this, adLayout, BuildConfig.CJ_SPLASH_AD, new AdListenera() {
                @Override
                public void adClose() {
                    goToHome();
                }

                @Override
                public void adError(HZAdError adError) {
                    goToHome();
                }

                @Override
                public void adShow() {
                    AnalyticsUtils.INSTANCE.logEvent("qd_ad_succeed");
                }
            });
        }

        if (showIntersAD) {
            AdLoadManager.INSTANCE.showInterstitialAd(this, BuildConfig.CJ_SPLASH_AD, new AdListenera() {
                @Override
                public void adError(HZAdError adError) {
                    goToHome();
                }

                @Override
                public void adClose() {
                    goToHome();
                }

                @Override
                public void adShow() {
                    AnalyticsUtils.INSTANCE.logEvent("qd_ad_succeed");
                }
            });
        }
    }

    private void goToHome() {
        migrateTo(MainActivity.class);
        finish();
    }

    private void whenLoadAD(int i) {
        String msg = "qd_ad_ready_" + (i+1)*3 + "s";
        AnalyticsUtils.INSTANCE.logEvent(msg);
        showToast(msg);
        LogUtils.e(TAG, "whenLoadAD   i = " + i);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_splash;
    }

    @Override
    protected void initView() {
        logo = (ImageView) findViewById(R.id.logo);
        appName = (TextView) findViewById(R.id.app_name);
        pb = (ProgressBar) findViewById(R.id.pb);
        protocolContainerLl = (LinearLayout) findViewById(R.id.protocol_container_ll);
        agreeBt = (Button) findViewById(R.id.agree_bt);
        protocolTv = (TextView) findViewById(R.id.protocol_tv);

        cancleIv = findViewById(R.id.cancel_iv);

        adLayout = findViewById(R.id.adLayout);
    }

    @Override
    protected void initEvent() {
        cancleIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AnalyticsUtils.INSTANCE.logEvent("jujuexy");
                finish();
            }
        });
        agreeBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AnalyticsUtils.INSTANCE.logEvent("tongyixy");
                App.spUtils.putBoolean(Constant.IS_AGREE_PRIVACE, true);
                goToHome();
            }
        });
    }

    private void showAgreeProtocolLayout(){
        //进入签署协议界面
        AnalyticsUtils.INSTANCE.logEvent("qianxieyi");
        protocolContainerLl.setVisibility(View.VISIBLE);
        pb.setVisibility(View.GONE);
        cancleIv.setVisibility(View.VISIBLE);

        setTextViewClick();
    }

    private void setTextViewClick() {
        protocolTv.setText(getString(R.string.read_our)+ " ");
        // 设置需要点击的文字
        SpannableString privacySp = new SpannableString(getString(R.string.privacy_policy));
        // 设置需要点击文字的样式
        privacySp.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                // 点击之后需要做的操作
                Intent intent = new Intent(SplashActivity.this, ProtocolActivity.class);
                intent.putExtra(ProtocolActivity.TYPE, ProtocolActivity.PRIVACY_POLICY);
                startActivity(intent);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                // 设置可点击文字的颜色
                ds.setColor(getResources().getColor(R.color.basic));
                ds.setUnderlineText(false);
            }
            // 0-->privacySp.length()这个长度就是需要点击的文字长度
        }, 0, privacySp.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 将需要点击的文字添加到我们的TextView中
        protocolTv.append(privacySp);
        // 继续添加不需要点击的文字组装TextView
        protocolTv.append(new SpannableString(". " + getString(R.string.tap_agree_continue_) + " "));
        // 设置需要点击的文字
        SpannableString termsSp = new SpannableString(getString(R.string.terms_of_service));
        // 设置需要点击文字的样式
        termsSp.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                // 点击之后需要做的操作
                Intent intent = new Intent(SplashActivity.this, ProtocolActivity.class);
                intent.putExtra(ProtocolActivity.TYPE, ProtocolActivity.TERMS_OF_SERVERS);
                startActivity(intent);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                // 设置可点击文字的颜色
                ds.setColor(getResources().getColor(R.color.basic));
                ds.setUnderlineText(false);
            }
            // 0-->privacySp.length()这个长度就是需要点击的文字长度
        }, 0, termsSp.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        protocolTv.append(termsSp);
        protocolTv.setMovementMethod(LinkMovementMethod.getInstance());

    }

    @Override
    public void onBackPressed() {

    }
}